<template>
 <!-- 甲供清单 -->
    <div>
        <div class="e-table" style="background-color: #fff" v-if="showTable">
            <!-- 头部buttons -->
            <div class="top" v-if="isAdd">
                <div class="left">
                    <div >
                        <el-button size="small" class="btn-greenYellow" @click="importList"
                        >新增</el-button>
                    </div>
                </div>
            </div>
            <div class="e-tree-table">
                <div class="errorMsg" v-if="errorMsg.length>0">
                <span >
                    {{ errorMsg.join(',') }}
                </span>
            </div>
                <el-table
                        ref="tableRef"
                        border
                        style="width: 100%"
                        row-key="billId"
                        :data="tableData"
                        :tree-props="{
                            children: 'children',
                            hasChildren: 'hasChildren'
                        }"
                        :load="onload"
                        lazy
                        :row-class-name="tableRowClassName"
                        class="table"
                        :max-height="$store.state.tableHeight"
                        v-sortTable="{ 'tableData': tableData, '_this': this, 'ref': 'tableRef' }"
                    >
                        <el-table-column prop="code" label="操作" fixed width="200" align="left">
                            <template slot-scope="{ row }">
                                <div class="oparation_box">
                                    <img src="@/assets/btn/sub.png" class="add_sub"
                                        @click="addChilden(row)"
                                        v-if="row.hierarchyType === 1 && isAdd"
                                        title="添加子级"
                                     />
                                    <i class="el-icon-delete"
                                        style="font-size: 24px; color: #e9513e;"
                                        v-if="isAdd"
                                        @click="onDelNode(row)"
                                        title="删除"
                                    ></i>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="supplyType"
                            label="甲供类型"
                            width="200"
                            fixed
                        >
                            <template slot-scope="{ row }">

                                <el-select
                                    v-if="row.hierarchyType === 1  && isAdd"
                                    v-model="row.supplyType"
                                    @change="changeSupplyType(row)"
                                >
                                    <el-option
                                        v-for="item in supplyType"
                                        :value="item.value"
                                        :label="item.label"
                                        :key="item.value"
                                        :disabled="isDisabled(item.value)"
                                    >
                                    </el-option>
                                </el-select>
                                <span v-else>
                                    <span v-if="row.hierarchyType === 1">{{  row.supplyType ? supplyType.find(x=>x.value === row.supplyType).label:'' }}</span>
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="equipmentType"
                            label="设备类别"
                            min-width="200"
                            fixed
                        >
                            <template slot-scope="{ row }">
                                <el-input v-model="row.equipmentType" v-if="row.hierarchyType === 2 && isAdd" readonly>
                                    <i
                                        class="
                                            el-icon-document-copy
                                        "
                                        slot="suffix"
                                        id="select"
                                        @click="selectMaterialType(row)"
                                    >
                                    </i>
                                </el-input>
                                <span v-else>{{ row.equipmentType }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="equipmentName"
                            label="设备名称"
                            width="200"
                            fixed
                        >
                        </el-table-column>
                        <el-table-column
                            prop="unit"
                            label="计量单位"
                            width="120"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="number"
                            label="数量" class-name="historyData"
                            width="120"
                        >
                            <template slot-scope="{ row }">
                                    <el-input v-if="row.hierarchyType === 2 && isEdit" v-model="row.number" @change="onCalcAmount(row,'quantityUpdateFlag')" @input.native="isFourInputJust"></el-input>
                                        <span v-else>{{ row.unitPrice }}</span>
                                        <historyUpdateTable
                                            v-if="checkEmpty(row.numberRecords)"
                                            @clickIcon="clickIcon(row.numberRecords)"
                                        />
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="unitPrice"
                            label="单价" class-name="historyData"
                            width="120"
                            align="right"
                        >
                            <template slot-scope="{ row }">
                                    <el-input v-if="row.hierarchyType === 2 && isEdit" v-model="row.unitPrice" @change="onCalcAmount(row,'unitPriceUpdateFlag')" v-enterJustFloat></el-input>
                                    <span v-else>{{ row.unitPrice }}</span>
                                    <historyUpdateTable
                                        v-if="checkEmpty(row.priceRecords)"
                                        @clickIcon="clickIcon(row.priceRecords)"
                                    />
                            </template>
                        </el-table-column>
                        <el-table-column prop="amount" width="120" label="金额" class-name="historyData" align="left">
                        </el-table-column>
                </el-table>
            </div>
         </div>
    </div>
</template>
<script>
import { toLocation, vueDom } from '@/utils/common.js'
import { uidBuilder } from '@/api/base/uid.js'
import { getUnit } from '@/api/subcontractApi/currency.js'
import { isFourInput, isNumInput, isTwoInput, isFourInputJust } from '@/utils/rules.js'
import { mapState, mapMutations, mapActions } from 'vuex'
import { selectDataClient } from '@/utils/common'
import historyUpdateTable from '@/pages/subcontract/components/historyUpdateTable.vue'
import fn from '@/utils/checkEmpty.js'
export default {
    props: {
        detailsOfProposed: {
            type: Array,
            default: function () {
                return []
            }
        },
        tenderClass: {
            type: String,
            default: ''
        },
        billid: {
            type: String,
            default: ''
        },
        contractListTable: {
            type: Array,
            default: function () {
                return []
            }
        },
        errorMsg: {
            type: Array,
            default: function () {
                return []
            }
        },
        isBidding: {
            type: Boolean,
            default: false
        },
        mainInfo: {
            type: Object,
            default: function () {
                return {}
            }
        },
        auditState: {
            type: Object,
            default: function () {
                return {
                    canAudit: false,
                    canModify: true,
                    canUndoAudit: false,
                    freeNextUnits: [],
                    isFree: false,
                }
            }
        },
        //是否可以新增
        isAdd: {
            default: true
        },
        //是否可以编辑
        isEdit: {
            default: true
        },
        subcontract: { //接口
        },
        state: { //流程状态
            type: Number
        }
    },
    model: {
        prop: 'contractListTable',
        event: 'change'
    },
    computed: {
        tenderId () {
            return this.$route.query.billid
        },
        ...mapState({
            materialList: state => state.contract.ctClassify.materialList,
            supplyType: state => state.contract.ctClassify.supplyTypeList,
            unitMeasure: state => state.equip.equipData.unitMeasure, //计量单位
        }),
        //判断数据是否为空
        checkEmpty () {
            return datas=>{
                return !fn.checkEmpty(datas)
            }
        },
        //甲供类型禁用项
        isDisabled () {
            return value =>{
                const supplyTypeList = this.tableData.filter(x=>(x.supplyType && x.changeType !== -1)).map(x=>x.supplyType)
                const obj = supplyTypeList.find(x=>x == value)
                if(obj) {
                    return true
                }else{
                    return false
                }
            }
        },
    },
    components: {
        historyUpdateTable,
    },
    watch: {
        contractListTable: {
            handler (newName) {
                this.tableData = newName
            },
            immediate: false,
            deep: true
        },
        tableData: {
            handler (newName) {
                this.$emit('change', newName)
            },
            immediate: true,
            deep: true
        },
    },
    data () {
        return {
            detailsOfProposedArr: [],
            tableData: [],
            mapTableData: {},
            addList: [], // 缓存新增数据
            unitList: [],
            searchKey: '',
            isSearch: false,
            addFlag: true,
            materialListTeam: [], //存储执行队列
            materialListIndex: 0,
            showTable: true,
        }
    },
    created () {
        this.getData()
        this.getDicValue()
    },
    mounted () {
        vueDom(
            // 默认0为选中项
            () => {
                $('.el-tree-node:first')?.addClass('is-current')
            },
            () => {
                return $('.el-tree-node:first')?.attr('class')?.includes('is-current')
            }
        )
        getUnit().then(res=>{
            let arr = res.map(x=>{
                let obj = {
                    value: '',
                    label: '',
                }
                obj.value = x.kvValue
                obj.label = x.kvKey
                return obj
            })
            this.unitList = arr
        })
        this.setUnitMeasur()
    },
    methods: {
        ...mapMutations(
            'contract', ['setMaterialList']
        ),
        ...mapMutations(['setHistoryTableData', 'setSelectedInfo']),
        ...mapActions(
            'contract', ['setUnitMeasur']
        ),
        //获取当前使用的字典
        getDicValue () {
            this.$store.dispatch('equip/setUnitMeasur')//更新计量单位
        },
        // 获取列表数据
        getData () {
            this.showTable = false
            //获取设备清单
            this.subcontract.getEquipmentList({
                sourceId: this.billid,
            }).then(res => {
                res = res.code ? [] : res
                res.forEach(item=>{
                    if(this.state === 1) {
                        item.quantityUpdateFlag = false
                        item.unitPriceUpdateFlag = false
                        item.amountUpdateFlag = false
                    }
                })
                //平级列表转成树形结构
                let arr = []
                const fn = (data, parentId)=>{
                    let arr = res.filter(x=>x.parentId === parentId)
                    if(arr.length > 0) {
                        arr.forEach(item=>{
                            let isDetailed = res.find(x=>x.parentId === item.billId)
                            item.hasChildren = isDetailed ? true : false
                            item.changeType = 0
                            item.children = []
                            if(item.hasChildren) {
                                fn(item.children, item.billId)
                            }
                            this.mapTableData[item.billId] = item
                            data.push(item)
                        })
                    }
                }
                fn(arr, '0')
                this.tableData = arr
                this.mapTableData['0'] = {
                    children: this.tableData
                }
                this.showTable = true
            })
        },
        // 通过id获取子级数据
        async getById (billId) {
            const params = {
                parentId: billId,
                sourceId: this.billid
            }
            let result = await this.getTableData(params)
            result.forEach(item=>{
                item.hasChildren = item.isDetailed ? false : true
                item.changeType = 0
            })
            return result
        },
        importList () {
            this.showClient()
        },
        async showClient () {
            const uid = await this.uidBuilder({ num: 1 })
            let obj = {
                'amount': 0,
                'billId': uid,
                'children': [],
                'equipmentType': '',
                'hierarchyType': 1,
                'mainMaterialFlag': true,
                'name': '',
                'number': 0,
                'parentId': '0',
                'sourceId': this.billid,
                'unit': '',
                'unitPrice': 0,
                'supplyType': '',
                hasChildren: false,
                changeType: 1,
                isNew: true
            }
            this.tableData.push(obj)
            this.mapTableData['0'] = {
                children: this.tableData
            }
        },
        async onload (row, treeNode, resolve) {
            let result
            if(row.children.length > 0) {
                result = row.children
            }else{
                // 如果有缓存数据，说明是点击的 “添加子级” 按钮
                if (this.addList.length > 0) {
                    result = result.concat(this.addList)
                    this.addList = []
                }
            }
            row.treeNode = treeNode
            row.resolve = resolve
            row.children = result
            this.mapTableData[row.billId] = row

            resolve(result)
        },
        // 添加子级
        async addChilden (row) {
            selectDataClient({
                SelectServiceToken: '/facilitybase/equipment/getEquipmentCategoryAll', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify({
                    'categoryId': '00000',
                    'isUpdate': false,
                    'keyword': ''
                }),
                Title: '选择设备' // 标题
            }).then(async val => {
                if(val.length === 0) return
                let uids = await this.uidBuilder({ num: val.length })
                uids = val.length > 1 ? uids : [uids]
                val.forEach((item, index)=>{
                    const { billId } = row
                    const { hierarchyType } = row
                    const addData = {
                        'amount': 0,
                        'children': [],
                        'mainMaterialFlag': true,
                        'name': '',
                        'number': 0,
                        'sourceId': this.billid,
                        'unit': '',
                        'unitPrice': 0,
                        'supplyType': row.supplyType,
                        'hierarchyType': hierarchyType + 1,
                        parentId: billId,
                        listIsDetailed: false,
                        billId: uids[index], //本级ID
                        hasChildren: false,
                        changeType: 1,
                        isNew: true,
                        equipmentType: item.categoryName,
                        equipmentTypeId: item.categoryId,
                        equipmentName: item.equipmentName,
                        equipmentId: item.equipmentId,
                    }
                    const unit = this.unitMeasure.find(x=>x.value == item.unit)
                    addData.unit = unit ? unit.label : ''
                    const tableRef = this.$refs.tableRef
                    if (!this.mapTableData[billId]) {
                        // 缓存新增数据
                        this.addList.push(addData)
                        // 如果是最子级，则设为目录
                        if (!row.hasChildren) {
                            row.children = row.children ? row.children : []
                            row.children = row.children.length > 0 ? row.children.push(addData) : [addData]
                            row.hasChildren = true
                            this.mapTableData[row.billId] = row
                            // 切换展开状态
                            this.$nextTick(() => {
                                // tableRef.toggleRowExpansion(row, true)
                                tableRef.store.loadOrToggle(row)
                            })
                        // }
                        } else {
                            // 展开子级
                            // tableRef.store.loadData(row, billId)
                            tableRef.store.loadOrToggle(row)
                        }
                    } else {
                        // 已经展开，则直接添加
                        row.children.push(addData)
                        row.hasChildren = true
                    }
                    // 定位到新添加行
                    toLocation(addData)
                })

            })

        },
        onDelNode (row) {
            // 如果是新增的，则直接删除
            if (row.changeType === 1) {
                const siblings = this.mapTableData[row.parentId].children
                const index = siblings.findIndex(item => item.billId === row.billId)
                siblings.splice(index, 1)
            } else {
                // 否则先提示，再删除
                this.clientPop('err', this.oneDeleteListErr, () => {
                    const siblings = this.mapTableData[row.parentId].children
                    const index = siblings.find(item => item.billId === row.billId)
                    index.changeType = -1
                    this.onDelNodeChild(index)
                    this.onCalcAmount(index)
                    index.changeType = -1

                    this.isDetailed = false
                    const siblings1 = this.mapTableData[row.parentId].children
                    for(let i = 0;i < siblings1.length;i++) {
                        if(siblings1[i].changeType !== -1) {
                            this.isDetailed = true
                            break
                        }
                    }
                    this.mapTableData[row.parentId].isDetailed = !this.isDetailed
                    this.mapTableData[row.parentId].hasChildren = this.isDetailed
                    this.$refs.tableRef.store.loadOrToggle(this.mapTableData[row.parentId])
                })
            }
        },
        //删除下级
        onDelNodeChild (row) {
            const fn = data=>{
                for(let i = 0;i < data.length;i++) {
                    if(data[i].changeType === 1) {
                        data.splice(i, 1)
                        i--
                    }else{
                        data[i].changeType = -1
                    }
                    if(data[i].children.length > 0) {
                        fn(data[i].children)
                    }
                    this.mapTableData[data[i].billId] = data[i]
                }
            }
            if(row.children.length > 0) {
                fn(row.children)
            }
        },
        // 输入后计划金额
        onCalcAmount (row, feild) {
            if(this.state === 1) {
                row[feild] = true
            }
            row.amount = row.changeType !== -1 ?  parseFloat(((row.number ? row.number : row.number) * (row.unitPrice ? row.unitPrice : 0)).toFixed(2)) : 0
            if(row.changeType !== -1) {
                row.changeType = row.changeType === 1 ? 1 : 2
            }
            // 向上汇总金额
            this.recurCount({
                parentId: row.parentId,
                rootId: '0',
                listField: 'billId',
                parentField: 'parentId',
                row
            })
        },
        // 递归统计父级
        recurCount ({ parentId, rootId, listField, parentField, row }) {
            // 到根节点
            if (parentId === rootId) {
                return
            }
            const parent = this.mapTableData[parentId]
            // 统计所有同级
            let countSibling = parent.children.reduce((prev, item) => {
                item.amount = item.amount ? parseFloat(item.amount) : 0
                return prev + (item.changeType !== -1 ? item.amount : 0)
            }, 0)
            // 赋值汇总数据给父级
            countSibling = typeof (countSibling) === 'string' ? parseFloat(countSibling) : countSibling
            parent.amount = parseFloat(countSibling.toFixed(2))
            if(parent.changeType !== -1) {
                parent.changeType = parent.changeType === 1 ? 1 : 2
            }
            // 未到根节点则继续遍历父节点
            return this.recurCount({
                parentId: parent[parentField],
                rootId,
                listField,
                parentField,
                row,
            })
        },
        tableRowClassName ({ row }) {
            if(row.changeType === -1) {
                if(row.hasChildren) {
                    return `class-${row.billId} row-hide`
                }else{
                    return `class-${row.billId}  row-hide hide-icon`
                }
            }else{
                if(row.hasChildren) {
                    return `class-${row.billId} row-show`
                }else{
                    return `class-${row.billId}  row-show hide-icon`
                }
            }

        },

        async uidBuilder (params) {
            let temp = ''
            await uidBuilder(params).then(res => {
                temp = res.length === 1 ? res[0] : res
            })
            return temp
        },
        // refreshLoadTree (parentId) {
        //     // 根据父级id取出对应节点数据
        //     // const { row, treeNode, resolve } = this.mapTableData[parentId]
        //     let children = this.mapTableData[parentId].children
        //     const tableRef = this.$refs.tableRef
        //     this.$set(tableRef.store.states.lazyTreeNodeMap, parentId, children)
        // },

        isFourInput (event) {
            isFourInput(event)
        },
        isFourInputJust (event) {
            isFourInputJust(event)
        },
        isNumInput (event) {
            isNumInput(event)
        },
        isTwoInput (event) {
            isTwoInput(event)
        },
        //单价类型切换
        unitPriceTypeChange (row) {
            const fn = data=>{
                data.forEach(item=>{
                    item.unitPriceType = row.unitPriceType
                    if(!item.isDetailed) {
                        fn(item.children)
                    }
                    this.mapTableData[row.billid] = row
                })
            }
            if(!row.isDetailed) {
                fn(row)
            }else{
                this.mapTableData[row.billid] = row
            }
        },
        //单价切换
        unitPriceChange (row) {
            row.children.forEach(item=>{
                item.unitPrice = row.unitPrice
                this.mapTableData[item.billid] = item
                this.onCalcAmount(item)
            })
            this.mapTableData[row.billid] = row
        },
        //数量切换
        quantityChange (row) {
            const parent = this.mapTableData[row.parentId]
            // 统计所有同级
            const countSibling = parent.children.reduce((prev, item) => {
                return prev + Math.round(item.changeType !== -1 ? item.quantity : 0)
            }, 0)
            // 赋值汇总数据给父级
            parent.quantity = countSibling // 赋值汇总数据给父级
        },
        selectMaterialType (row) {
            selectDataClient({
                SelectServiceToken: '/facilitybase/equipment/getEquipmentCategoryAll', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [''], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify({
                    'categoryId': '00000',
                    'isUpdate': false,
                    'keyword': ''
                }),
                Title: '选择设备' // 标题
            }).then(val => {
                let obj = {
                    'categoryName': val[0].categoryName,
                    'categoryId': val[0].categoryId,
                    'equipmentId': val[0].equipmentId,
                    'equipmentName': val[0].equipmentName,
                    'unit': val[0].unit
                }
                row.equipmentType = obj.categoryName
                row.equipmentTypeId = obj.categoryId
                row.equipmentName = obj.equipmentName
                row.equipmentId = obj.equipmentId
                row.changeType = row.changeType === 1 ? 1 : 2
                row.number = 0
                row.unitPrice = 0
                row.amount = 0
                const unit = this.unitMeasure.find(x=>x.value == obj.unit)
                row.unit = unit ? unit.label : ''
            })
        },
        clickIcon (list) {
            this.setHistoryTableData(list)
        },
        //切换甲供类型
        changeSupplyType (row) {
            row.changeType = row.changeType === 1 ? 1 : 2
            const fn = row=>{
                if(row.children.length > 0) {
                    row.children.forEach(item=>{
                        item.supplyType = row.supplyType
                        item.changeType = item.changeType === 1 ? 1 : 2
                        fn(item)
                    })
                }
            }
            fn(row)
        }
    }
}
</script>
<style lang='scss' scoped>
    ::v-deep .hide-icon{
        .el-table__expand-icon{
            display: none;
        }
    }
    ::v-deep.el-table__row{
        .cell{
            display: flex;
            align-items: center;
        }
        td:nth-child(6),td:nth-child(7),td:nth-child(8){
            .cell{
                justify-content: flex-end;
            }
        }
    }
    ::v-deep .el-popover__reference-wrapper{
        display: flex;
        height: 100%;
    }
</style>
